package jgl.vajra.kingkong.manager;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.fragment.app.FragmentActivity;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import jgl.vajra.kingkong.bean.OnLinePayBean;
import jgl.vajra.kingkong.event.PayStatusEvent;
import jgl.vajra.kingkong.event.PaymentSuccessEvent;
import jgl.vajra.kingkong.widget.manager.RxJavaHttpManager;
import jgl.vajra.kingkong.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.kingkong.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.utils.UIUtils;

public class PayManager {

    private IWXAPI msgApi;
    private static final int SDK_ALI_PAY_FLAG = 1;
    private static final String TAG = "PayInfo========>>";

    private PayManager() {

    }


    private static class PayManagerSingleton {
        private static final PayManager INSTANCE = new PayManager();

    }

    public static PayManager getInstance() {
        return PayManagerSingleton.INSTANCE;
    }


   /* public void payBalance(final FragmentActivity activity, String orderId, String amount) {
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", AEACCoder.encrypt(orderId + "&&" + amount));
        map.put("tag", 7);

        RetrofitJsonManager.getInstance().getApiService().payWxCallback(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(true, null) {
                    @Override
                    public void _onNext(String wxPayBean) {
                        payCallback(activity, orderId, amount, 7);
                    }
                });
    }*/

    public void payWX(final FragmentActivity activity, String orderId, String amount,int overtime) {
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", AEACCoder.encrypt(orderId + "&&" + amount));
        map.put("tag", 1);
        map.put("overtime", overtime);

        RetrofitJsonManager.getInstance().getApiService().payWx(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<OnLinePayBean>(true, null) {
                    @Override
                    public void _onNext(OnLinePayBean wxPayBean) {
                        msgApi = WXAPIFactory.createWXAPI(activity, null);
                        msgApi.registerApp("wx9f1fa58451efa9b2");
                        PayReq request = new PayReq();
                        request.appId = wxPayBean.appid;
                        request.partnerId = wxPayBean.mch_id;
                        request.prepayId = wxPayBean.prepay_id;
                        request.packageValue = "Sign=WXPay";
                        request.nonceStr = wxPayBean.nonce_str;
                        request.timeStamp = wxPayBean.timestamp;
                        request.sign = wxPayBean.sign;
                        msgApi.sendReq(request);
                    }
                });
    }


    public void payRechargeWx(final FragmentActivity activity, String orderId, int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", AEACCoder.encrypt(orderId + "&&" + id));
        map.put("tag", 1);

        RetrofitJsonManager.getInstance().getApiService().payRechargeWx(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<OnLinePayBean>(true, null) {
                    @Override
                    public void _onNext(OnLinePayBean wxPayBean) {
                        msgApi = WXAPIFactory.createWXAPI(activity, null);
                        msgApi.registerApp("wx9f1fa58451efa9b2");
                        PayReq request = new PayReq();
                        request.appId = wxPayBean.appid;
                        request.partnerId = wxPayBean.mch_id;
                        request.prepayId = wxPayBean.prepay_id;
                        request.packageValue = "Sign=WXPay";
                        request.nonceStr = wxPayBean.nonce_str;
                        request.timeStamp = wxPayBean.timestamp;
                        request.sign = wxPayBean.sign;
                        msgApi.sendReq(request);
                    }
                });
    }

    /**
     * 显示支付宝签名
     */
    public void payAli(final FragmentActivity activity, String orderId, String amount,int overtime) {
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", AEACCoder.encrypt(orderId + "&&" + amount));
        map.put("tag", 3);
        map.put("overtime", overtime);
        RetrofitJsonManager.getInstance().getApiService().payWxCallback(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(true, null) {
                    @Override
                    public void _onNext(String data) {
                        // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
                        //支付宝支付请求所需的签名字符串
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(activity);
                                Map<String, String> result = alipay.payV2(data, true);
                                Logger.d(TAG + result.toString());

                                Message message = new Message();
                                message.what = SDK_ALI_PAY_FLAG;
                                message.obj = result;
                                mHandler.sendMessage(message);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }
                });

        // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        //支付宝支付请求所需的签名字符串
      /*  Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                String orderInfo = "app_id=2015052600090779&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22314VYGIAGG7ZOYY%22%7D&charset=utf-8&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2016-08-15%2012%3A12%3A15&version=1.0&sign=MsbylYkCzlfYLy9PeRwUUIg9nZPeN9SfXPNavUCroGKR5Kqvx0nEnd3eRmKxJuthNUx4ERCXe552EV9PfwexqW%2B1wbKOdYtDIb4%2B7PL3Pc94RZL0zKaWcaY3tSL89%2FuAVUsQuFqEJdhIukuKygrXucvejOUgTCfoUdwTi7z%2BZzQ%3D";

                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Logger.d(TAG + result.toString());

                Message message = new Message();
                message.what = SDK_ALI_PAY_FLAG;
                message.obj = result;
                mHandler.sendMessage(message);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();*/
    }

    /**
     * 显示支付宝签名
     */
    public void payRechargeAli(final FragmentActivity activity, String orderId, int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", AEACCoder.encrypt(orderId + "&&" + id));
        map.put("tag", 3);
        RetrofitJsonManager.getInstance().getApiService().payRechargeWxCallback(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(true, null) {
                    @Override
                    public void _onNext(String data) {
                        // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
                        //支付宝支付请求所需的签名字符串
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(activity);
                                Map<String, String> result = alipay.payV2(data, true);
                                Logger.d(TAG + result.toString());

                                Message message = new Message();
                                message.what = SDK_ALI_PAY_FLAG;
                                message.obj = result;
                                mHandler.sendMessage(message);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }
                });

        // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        //支付宝支付请求所需的签名字符串
      /*  Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                String orderInfo = "app_id=2015052600090779&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22314VYGIAGG7ZOYY%22%7D&charset=utf-8&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2016-08-15%2012%3A12%3A15&version=1.0&sign=MsbylYkCzlfYLy9PeRwUUIg9nZPeN9SfXPNavUCroGKR5Kqvx0nEnd3eRmKxJuthNUx4ERCXe552EV9PfwexqW%2B1wbKOdYtDIb4%2B7PL3Pc94RZL0zKaWcaY3tSL89%2FuAVUsQuFqEJdhIukuKygrXucvejOUgTCfoUdwTi7z%2BZzQ%3D";

                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Logger.d(TAG + result.toString());

                Message message = new Message();
                message.what = SDK_ALI_PAY_FLAG;
                message.obj = result;
                mHandler.sendMessage(message);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();*/
    }

    //支付宝返回数据handler
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message message) {
            switch (message.what) {
                case SDK_ALI_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    Map<String, String> map = (Map<String, String>) message.obj;
                    String resultStatus = map.get("resultStatus");
                    Logger.d(TAG + resultStatus);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     *
                     * @param activity
                     */
                    String result = "";
                    // 判断resultStatus 为9000则代表支付成功
//                    Log.i(TAG, resultStatus);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //支付成功
                        result = "支付成功";
                        EventBus.getDefault().post(new PayStatusEvent(true, 4));
//                        aliPaySuccess();
                    } else if ("6001".equals(resultStatus)) {
                        result = "您取消了支付";
                        EventBus.getDefault().post(new PayStatusEvent(false, 4));
                        // closeOrder();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        result = "支付失败";
                        EventBus.getDefault().post(new PayStatusEvent(false, 4));
                    }
//                    if (!TextUtils.isEmpty(result))
                    ToastUtils.showShort(result);
                    break;
                }
            }
        }
    };

    //余额支付
    public void payBalance(FragmentActivity activity, String orderId, String amount,int overtime) {
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", AEACCoder.encrypt(orderId + "&&" + amount));
        map.put("tag", 7);
        map.put("overtime", overtime);
        RetrofitJsonManager.getInstance().getApiService().payWxCallback(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(false, null) {
                    @Override
                    public void _onNext(String wxPayBean) {
                        EventBus.getDefault().post(new PaymentSuccessEvent());
                        activity.finish();
                    }

                    @Override
                    public void _onError(String errorMessage, int errorCode) {
                        super._onError(errorMessage, errorCode);
                        EventBus.getDefault().post(new PaymentSuccessEvent());
                        activity.finish();
                    }
                });
    }
}
